#include "../server.hpp"

class EchoServer
{
public:
    EchoServer(int port) : _server(port) {
        _server.SetThreadCount(2);
        _server.EnableInactiveRelease(10);
        _server.SetConnectedCallback(std::bind(&EchoServer::OnConnected, this, std::placeholders::_1));
        _server.SetClosedCallback(std::bind(&EchoServer::OnClosed, this, std::placeholders::_1));
        _server.SetMessageCallback(std::bind(&EchoServer::OnMessage, this, std::placeholders::_1, std::placeholders::_2));   
    }

    void Start() { _server.Start(); }

private:
    void OnConnected(const Connection::ptr &conn) {
        LOG(LogLevel::INFO) << "NEW CONNECTION: " << conn.get();
    }
    
    void OnClosed(const Connection::ptr &conn) {
        LOG(LogLevel::INFO) << "CLOSE CONNECTION: " << conn.get();
    }
    
    void OnMessage(const Connection::ptr &conn, Buffer* buf) {
        conn->Send(buf->ReadPosition(), buf->ReadAbleSize());
        buf->MoveReadOffset(buf->ReadAbleSize());
        conn->Shutdown();       // 最后实际上是在handlewrite这里关闭连接的
    }

private:
    TcpServer _server;
};